/**
 * @Filename：HttpUtil.java
 * @Author：caiqf
 * @Date：2013-9-23
 */
package com.temple.common.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;



@SuppressWarnings("all")
public class HttpUtil {

	private static final Log log = LogFactory.getLog(HttpUtil.class);
	private static final int TIME_OUT = 0 * 10000;                          //超时时间
	private static final String CHARSET = "utf-8";                         //编码格式
	private static final String PREFIX = "--";                            //前缀
	private static final String BOUNDARY = UUID.randomUUID().toString();  //边界标识 随机生成
	private static final String CONTENT_TYPE = "multipart/form-data";     //内容类型
	private static final String LINE_END = "\r\n";                        //换行

	/***
	 * 链接超时时长
	 */
	private static final Integer CONNECT_TIMEOUT = 60*1000;
	/**
	 * 读取超时时长
	 */
	private static final Integer READ_TIMEOUT= 60*1000;

	/**
	 * 
	 * HTTP协议GET请求方法
	 */
	public static String httpMethodGet(String url, String gb) {
		if (null == gb || "".equals(gb)) {
			gb = "UTF-8";
		}
		StringBuffer sb = new StringBuffer();
		URL urls;
		HttpURLConnection uc = null;
		BufferedReader in = null;
		try {
			urls = new URL(url);
			uc = (HttpURLConnection) urls.openConnection();
			uc.setRequestMethod("GET");
			uc.connect();
			in = new BufferedReader(new InputStreamReader(uc.getInputStream(),
					gb));
			String readLine = "";
			while ((readLine = in.readLine()) != null) {
				sb.append(readLine);
			}
			if (in != null) {
				in.close();
			}
			if (uc != null) {
				uc.disconnect();
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		} finally {
			if (uc != null) {
				uc.disconnect();
			}
		}
		return sb.toString();
	}

	/**
	 * 
	 * HTTP协议POST请求方法
	 */
	public static String httpMethodPost(String url, String params, String gb) {
		//判断走https 还是 走http请求
		if(null != url && !("").equals(url) && url.contains("https")){//走https请求方法
			return HttpsUtil.httpMethodPost(url, params);
		}else{
			if (null == gb || "".equals(gb)) {
				gb = "UTF-8";
			}
			StringBuffer sb = new StringBuffer();
			URL urls;
			HttpURLConnection uc = null;
			BufferedReader in = null;
			try {
				urls = new URL(url);
				uc = (HttpURLConnection) urls.openConnection();
				uc.setRequestMethod("POST");
				uc.setDoOutput(true);
				uc.setDoInput(true);
				uc.setUseCaches(false);
				uc.setRequestProperty("Content-Type",
						"application/x-www-form-urlencoded");
				uc.connect();
				DataOutputStream out = new DataOutputStream(uc.getOutputStream());
				out.write(params.getBytes(gb));
				out.flush();
				out.close();
				in = new BufferedReader(new InputStreamReader(uc.getInputStream(),
						gb));
				String readLine = "";
				while ((readLine = in.readLine()) != null) {
					sb.append(readLine);
				}
				if (in != null) {
					in.close();
				}
				if (uc != null) {
					uc.disconnect();
				}
			} catch (IOException e) {
				log.error(e.getMessage(), e);
			} finally {
				if (uc != null) {
					uc.disconnect();
				}
			}
			return sb.toString();
		}
	}

	/**
	 * 
	 * HTTP协议POST请求方法
	 */
	public static String httpMethodPost(String url,
			TreeMap<String, String> paramsMap, String gb) {
		if (null == gb || "".equals(gb)) {
			gb = "UTF-8";
		}
		String params = null;
		if (null != paramsMap) {
			params = getParamStr(paramsMap);
		}

		StringBuffer sb = new StringBuffer();
		URL urls;
		HttpURLConnection uc = null;
		BufferedReader in = null;
		try {
			urls = new URL(url);
			uc = (HttpURLConnection) urls.openConnection();
			uc.setDoOutput(true);
			uc.setDoInput(true);
			uc.setRequestMethod("POST");
			uc.setUseCaches(false);
			uc.connect();
			DataOutputStream out = new DataOutputStream(uc.getOutputStream());
			out.write(params.getBytes(gb));
			out.flush();
			out.close();
			in = new BufferedReader(new InputStreamReader(uc.getInputStream(),
					gb));
			String readLine = "";
			while ((readLine = in.readLine()) != null) {
				sb.append(readLine);
			}
			if (in != null) {
				in.close();
			}
			if (uc != null) {
				uc.disconnect();
			}
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		} finally {
			if (uc != null) {
				uc.disconnect();
			}
		}
		return sb.toString();
	}

	/**
	 * 
	 * HTTP协议POST请求方法
	 */
	public static String httpMethodPost2(String url,
			TreeMap<String, String> paramsMap, String gb) {
		if (null == gb || "".equals(gb)) {
			gb = "UTF-8";
		}
		String params = null;
		if (null != paramsMap) {
			params = getParamStr(paramsMap);
		}

		StringBuffer sb = new StringBuffer();
		URL urls;
		HttpURLConnection uc = null;
		BufferedReader in = null;
		try {
			urls = new URL(url);
			uc = (HttpURLConnection) urls.openConnection();
			uc.setDoOutput(true);
			uc.setDoInput(true);
			uc.setRequestMethod("POST");
			uc.setUseCaches(false);
			uc.connect();
			DataOutputStream out = new DataOutputStream(uc.getOutputStream());
			out.write(params.getBytes(gb));
			out.flush();
			out.close();
			in = new BufferedReader(new InputStreamReader(uc.getInputStream(),
					gb));
			String readLine = "";
			while ((readLine = in.readLine()) != null) {
				sb.append(readLine);
			}
			if (in != null) {
				in.close();
			}
			if (uc != null) {
				uc.disconnect();
			}
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		} finally {
			if (uc != null) {
				uc.disconnect();
			}
		}
		return sb.toString();
	}

	/**
	 *
	 * HTTP协议POST请求方法
	 */
	public static String httpMethodPost2(String url, String params, String gb) {
		if (null == gb || "".equals(gb)) {
			gb = "UTF-8";
		}
		StringBuffer sb = new StringBuffer();
		URL urls;
		HttpURLConnection uc = null;
		BufferedReader in = null;
		try {
			urls = new URL(url);
			uc = (HttpURLConnection) urls.openConnection();
			uc.setConnectTimeout(CONNECT_TIMEOUT);
			uc.setReadTimeout(READ_TIMEOUT);
			uc.setRequestMethod("POST");
			uc.setDoOutput(true);
			uc.setDoInput(true);
			uc.setUseCaches(false);
//			uc.setRequestProperty("user-agent", "MicroMessenger");
			uc.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded;charset=UTF-8");
			uc.connect();
			DataOutputStream out = new DataOutputStream(uc.getOutputStream());
			out.write(params.getBytes(gb));
			out.flush();
			out.close();
			in = new BufferedReader(new InputStreamReader(uc.getInputStream(),
					gb));
			String readLine = "";
			while ((readLine = in.readLine()) != null) {
				sb.append(readLine);
			}
			if (in != null) {
				in.close();
			}
			if (uc != null) {
				uc.disconnect();
			}
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		} finally {
			if (uc != null) {
				uc.disconnect();
			}
		}
		return sb.toString();
	}

	/**
	 * 
	 * HTTP协议POST请求添加参数的封装方法
	 */
	public static String getParamStr(TreeMap<String, String> paramsMap) {
		StringBuilder param = new StringBuilder();
		for (Iterator<Map.Entry<String, String>> it = paramsMap.entrySet().iterator(); it.hasNext();) {
			Map.Entry<String, String> e = it.next();
			param.append("&").append(e.getKey()).append("=").append(e.getValue());
		}
		return param.toString().substring(1);
	}
	/**
	 * HTTP协议post请求图片上传
	 */
	public static String uploadImg(String url,File file,TreeMap<String, String> map){
		String params = null;
		if (null != map) {
			params = getParamStr(map);
		}

		StringBuffer sb = new StringBuffer();
		URL urls;
		HttpURLConnection uc = null;
		FileInputStream inFile=null;
		BufferedReader in = null;
		try {
			urls = new URL(url);
			uc = (HttpURLConnection) urls.openConnection();
			uc.setDoOutput(true);
			uc.setDoInput(true);
			uc.setRequestMethod("POST");
			uc.setRequestProperty("content-type", "multipart/form-data");
			uc.setRequestProperty("charset", "utf-8");
			uc.setUseCaches(false);
			uc.connect();
			 inFile= new FileInputStream(file);
			int img_size = inFile.available();
			byte[] buffer = new byte[1024];
			byte[] result = new byte[img_size];
			int count = 0;
			int rbyte = 0;
			while (count < img_size) {
				rbyte = inFile.read(buffer);
				for (int i = 0; i < rbyte; i++) {
					result[count + i] = buffer[i];
				}
				count += rbyte;
			}
			DataOutputStream out = new DataOutputStream(uc.getOutputStream());
			out.write(result);
			out.write(params.getBytes("UTF-8"));
			out.flush();
			out.close();
			in = new BufferedReader(new InputStreamReader(uc.getInputStream(),
					"UTF-8"));
			String readLine = "";
			while ((readLine = in.readLine()) != null) {
				sb.append(readLine);
			}
			if (in != null) {
				in.close();
			}
			if (uc != null) {
				uc.disconnect();
			}
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		} finally {
			if (uc != null) {
				uc.disconnect();
			}
		}
		return sb.toString();
	}

	/**
	 *
	 * HTTP协议POST请求方法
	 */
	public static String httpMethodPost(String url, String params) {
		if(null != url && !("").equals(url) && url.contains("https")){//走https请求方法
			return HttpsUtil.httpMethodPost(url, params);
		}else{
			StringBuffer sb = new StringBuffer();
			URL urls;
			HttpURLConnection uc = null;
			BufferedReader in = null;
			try {
				urls = new URL(url);
				uc = (HttpURLConnection) urls.openConnection();
				uc.setRequestMethod("POST");
				uc.setDoOutput(true);
				uc.setDoInput(true);
				uc.setUseCaches(false);
				uc.setRequestProperty("Content-Type",
						"application/x-www-form-urlencoded");
				uc.connect();
				DataOutputStream out = new DataOutputStream(uc.getOutputStream());
				out.write(params.getBytes());
				out.flush();
				out.close();
				in = new BufferedReader(new InputStreamReader(uc.getInputStream()
				));
				String readLine = "";
				while ((readLine = in.readLine()) != null) {
					sb.append(readLine);
				}
				if (in != null) {
					in.close();
				}
				if (uc != null) {
					uc.disconnect();
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (uc != null) {
					uc.disconnect();
				}
			}
			return sb.toString();
		}
	}

	public static String getParamStr(HashMap<String, Object> paramsMap) {
		StringBuilder param = new StringBuilder();
		for (Iterator<Map.Entry<String, Object>> it = paramsMap.entrySet().iterator(); it.hasNext();) {
			Map.Entry<String, Object> e = it.next();
			param.append("&").append(e.getKey()).append("=").append(e.getValue());
		}
		return param.toString().substring(1);
	}


	/**
	 * HTTP协议post请求图片上传
	 */
	public static String uploadImg(String url,InputStream is){
		StringBuffer sb = new StringBuffer();
		URL urls;
		HttpURLConnection uc = null;
		BufferedReader in = null;
		try {
			urls = new URL(url);
			uc = (HttpURLConnection) urls.openConnection();
			uc.setDoOutput(true);
			uc.setDoInput(true);
			uc.setRequestMethod("POST");
			uc.setRequestProperty("content-type", "multipart/form-data");
			uc.setRequestProperty("charset", "utf-8");
			uc.setUseCaches(false);
			uc.connect();
			int img_size = is.available();
			byte[] buffer = new byte[1024];
			byte[] result = new byte[img_size];
			int count = 0;
			int rbyte = 0;
			while (count < img_size) {
				rbyte = is.read(buffer);
				for (int i = 0; i < rbyte; i++) {
					result[count + i] = buffer[i];
				}
				count += rbyte;
			}
			DataOutputStream out = new DataOutputStream(uc.getOutputStream());
			out.write(result);
			out.flush();
			out.close();
			in = new BufferedReader(new InputStreamReader(uc.getInputStream(),
					"UTF-8"));
			String readLine = "";
			while ((readLine = in.readLine()) != null) {
				sb.append(readLine);
			}
			if (in != null) {
				in.close();
			}
			if (uc != null) {
				uc.disconnect();
			}
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		} finally {
			if (uc != null) {
				uc.disconnect();
			}
		}
		return sb.toString();
	}

	public static String upload(String tourl ,Map<String, String> strParams,Map<String, File> fileParams) {
		HttpURLConnection conn = null;
		StringBuilder response = new StringBuilder();
		try {
			URL url = new URL(tourl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setReadTimeout(TIME_OUT);
			conn.setConnectTimeout(TIME_OUT);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);//Post 请求不能使用缓存
			//设置请求头参数
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setRequestProperty("Content-Type", CONTENT_TYPE+";boundary=" + BOUNDARY);
			/**
			 * 请求体
			 */
			//上传参数
			DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
			//getStrParams()为一个
			String string = "";
			if (strParams!=null) {
				string = getStrParams(strParams).toString();
			}
			dos.writeBytes(string);
			dos.flush();

			//文件上传
			if (fileParams!=null) {
				StringBuilder fileSb = new StringBuilder();
				for (Map.Entry<String, File> fileEntry: fileParams.entrySet()){
					fileSb.append(PREFIX)
							.append(BOUNDARY)
							.append(LINE_END)
							/**
							 * 这里重点注意： name里面的值为服务端需要的key 只有这个key 才可以得到对应的文件
							 * filename是文件的名字，包含后缀名的 比如:abc.png
							 */
							.append("Content-Disposition: form-data; name=\"file\"; filename=\""
									+ fileEntry.getKey() + "\"" + LINE_END)
							.append("Content-Type: image/jpg" + LINE_END) //此处的ContentType不同于 请求头 中Content-Type
							.append("Content-Transfer-Encoding: 8bit" + LINE_END)
							.append(LINE_END);// 参数头设置完以后需要两个换行，然后才是参数内容
					dos.writeBytes(fileSb.toString());
					dos.flush();
					InputStream is = new FileInputStream(fileEntry.getValue());
					byte[] buffer = new byte[1024];
					int len = 0;
					while ((len = is.read(buffer)) != -1){
						dos.write(buffer,0,len);
					}
					is.close();
					dos.writeBytes(LINE_END);
				}
				//请求结束标志
				dos.writeBytes(PREFIX + BOUNDARY + PREFIX + LINE_END);
				dos.flush();
				dos.close();

			}
			//读取服务器返回信息
			if (conn.getResponseCode() == 200) {
				InputStream in = conn.getInputStream();
				BufferedReader reader = new BufferedReader(new InputStreamReader(in));
				String line = null;
				while ((line = reader.readLine()) != null) {
					response.append(line);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if (conn!=null){
				conn.disconnect();
			}
		}
		return response.toString();
	}

	/**
	 * 对post参数进行编码处理
	 * */
	private static StringBuilder getStrParams(Map<String,String> strParams){
		StringBuilder strSb = new StringBuilder();
		for (Map.Entry<String, String> entry : strParams.entrySet() ){
			strSb.append(PREFIX)
					.append(BOUNDARY)
					.append(LINE_END)
					.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINE_END)
					.append("Content-Type: text/plain; charset=" + CHARSET + LINE_END)
					.append("Content-Transfer-Encoding: 8bit" + LINE_END)
					.append(LINE_END)// 参数头设置完以后需要两个换行，然后才是参数内容
					.append(entry.getValue())
					.append(LINE_END);
		}
		return strSb;
	}
}
